#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include"Comm.hpp"
#include"InetAddr.hpp"
#include<unistd.h>

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " ip port" << std::endl;
        return 0;
    }
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(socket_fd < 0)
    {
        std::cerr << "create client socket error" << std::endl;
        exit(SOCKET_CREATE_ERROR);
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);
    InetAddr server(port, ip);
    int connect_ret = connect(socket_fd, server.Addr(), server.Len());
    if(connect_ret < 0)
    {
        std::cerr << "connect server error" << std::endl;
        exit(SOCKET_CONNECT_ERROR);
    }
    std::cout << "connect " << server.ToString() << " success" << std::endl;
    while(true)
    {
        std::cout << "Please Enter@ ";
        std::string line;
        std::getline(std::cin, line);
        int write_ret = write(socket_fd, line.c_str(), line.size());
        char buffer[1024];
        int read_ret = read(socket_fd, buffer, sizeof(buffer) - 1);
        if(read_ret > 0)
        {
            buffer[read_ret] = 0;
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}